<template>
    <div class='search'>
        <form action="/">
            <van-search v-model="value" show-action placeholder="请输入搜索关键词" @search="onSearch">
                <template #action>
                    <div @click="onSearch">搜索</div>
                </template>
            </van-search>
        </form>

        <h2>历史搜索记录</h2>
        <!-- 循环历史数据 -->
        <ul>
            <li v-for="(item,index) in history" :key="index" v-show="index<3">
                {{item}}
            </li>
        </ul>
        <button @click="clean">清空历史记录</button>
    </div>
</template>

<script>
    import {
        Dialog
    } from 'vant';
    export default {
        data() {
            return {
                value: "",
                history: JSON.parse(localStorage.getItem("history")) || []
            };
        },
        mounted() {},
        methods: {
            onSearch() {

                this.history.unshift(this.value);
                // 本地存储历史记录，转化字符串
                localStorage.setItem("history", JSON.stringify(this.history))
                // 跳转到搜索结果页面
                this.$router.push({
                    path: "/result",
                    query: {
                        val: this.value
                    }
                })
            },
            // 清空历史记录
            clean() {
                Dialog.confirm({
                        title: '标题',
                        message: '是否清空历史记录？',
                    })
                    .then(() => {
                        // 删除本地存储的数据
                        localStorage.removeItem("history");
                        // 删除页面里的数组里的数据
                        this.history = [];
                    })
                    .catch(() => {
                        // on cancel
                    });
            }
        },
    };
</script>

<style lang='scss'>

</style>